﻿using Mozi.HttpEmbedded.Extension;
using System;
using System.Collections.Generic;

namespace Mozi.Live.RTP
{
    /// <summary>
    /// RTCP APP报文
    /// </summary>
    public class RTCPAppPackage : AbsRTCPPackage
    {
        /// <summary>
        /// 源标识符 同步源|贡献源
        /// </summary>
        public uint Identifier { get; set; }
        /// <summary>
        /// 32bits
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// n*32bits
        /// </summary>
        public byte[] Data { get; set; }
        /// <summary>
        /// 包类型
        /// </summary>
        public override RTCPPackageType PackageType
        {
            get
            {
                return RTCPPackageType.APP;
            }
            set
            {
                return;
            }
        }
        /// <summary>
        /// 打包成数据流
        /// </summary>
        /// <returns></returns>
        public override byte[] Pack()
        {
            List<byte> buffer = new List<byte>();
            buffer.AddRange(PackHeader());
            buffer.AddRange(Identifier.ToBigEndian());
            byte[] name = System.Text.Encoding.ASCII.GetBytes(Name);
            byte[] name2 = new byte[4];
            Array.Copy(name, name2, name.Length > 4 ? 4 : name.Length);
            buffer.AddRange(name2);
            if (Data != null)
            {
                buffer.AddRange(buffer);
            }
            //最后计算长度
            byte[] data = buffer.ToArray();
            Length = (ushort)(data.Length / 4 - 1);
            Array.Copy(Length.ToBigEndian(), 0, data, 2, 2);
            return data;
        }
        /// <summary>
        /// 解析数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static new RTCPAppPackage Parse(byte[] data)
        {
            RTCPAppPackage pack = new RTCPAppPackage();
            byte[] head = new byte[4];
            Array.Copy(data, 0, head, 0, 4);
            pack.ParseHeader(head);
            pack.Identifier = data.GetBigEndianUInt32(4);
            pack.Name = System.Text.Encoding.ASCII.GetString(data, 8, 4);
            if (pack.Length > 0)
            {
                pack.Data = new byte[pack.Length];
                Array.Copy(data, 12, pack.Data, 0,pack.Length);
            }            
            return pack;
        }
    }
}
